package cn.chendd.example.jpa.user.dao;

import cn.chendd.example.jpa.user.entity.User;
import cn.chendd.example.jpa.user.repository.UserRepository;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Specification查询
 *
 * @author chendd
 * @date 2020/5/2 22:18
 */
@Repository
public class UserPageDao {

    @Resource
    private UserRepository userRepository;

    public Page<User> queryUsersPage(final User user , Integer page , Integer size) {
        Pageable pageable = PageRequest.of(page , size , Sort.by("name"));
        Page<User> pager = userRepository.findAll((Specification<User>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<>();
            //动态构造查询条件
            String name = user.getName();
            if(StringUtils.isNotEmpty(name)) {
                predicateList.add(criteriaBuilder.equal(root.get("name") , name));
            }
            String email = user.getEmail();
            if(StringUtils.isNotEmpty(email)) {
                predicateList.add(criteriaBuilder.like(root.get("email") , email + "%"));
            }
            Predicate[] predicates = new Predicate[predicateList.size()];
            predicateList.toArray(predicates);
            return criteriaQuery.where(predicates).getRestriction();
        }, pageable);
        return pager;
    }

}
